package com.xu.blog_after_end.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
    /**
     * MD5加密
     * @param str 待加密的字符串
     * @return 加密后的字符串
     */
    public static String code(String str) {
        try {
            // 获取 MessageDigest 实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 将字符串转换为字节数组并更新摘要
            md.update(str.getBytes());

            // 计算哈希值
            byte[] digest = md.digest();

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    public static void main(String[] args) {
        String input = "123456";
        String encoded = code(input);
        System.out.println("Original: " + input);
        System.out.println("MD5 Encoded: " + encoded);
    }
}
